<?php

if_get('/events', function ()
{/*{{{*/
    list(
        $inputs['name']
    ) = input_list(
        'name'
    );

    $inputs = array_filter($inputs, 'not_null');

    $events = dao('event')->find_all_by_column($inputs);

    return [
        'count' => count($events),
        'events' => array_build($events, function ($id, $event) {
            return [
                null,
                [
                    'id' => $event->id,
                    'name' => $event->name,
                    'create_time' => $event->create_time,
                    'update_time' => $event->update_time,
                ]
            ];
        }),
    ];
});/*}}}*/

if_post('/events/add', function ()
{/*{{{*/
    $name = input('name');
    otherwise_error_code('EVENT_REQUIRE_NAME', $name);

    $another_event = dao('event')->find_by_name($name);
    otherwise_error_code('EVENT_DUPLICATED', $another_event->is_null(), [':event_id' => $another_event->id]);

    $event = event::create(
        $name
    );

    return [
        'id' => $event->id,
    ];
});/*}}}*/

//todo::detail

if_post('/events/update/*', function ($event_id)
{/*{{{*/
    $name = input('name');

    $event = dao('event')->find($event_id);
    otherwise_error_code('EVENT_NOT_FOUND', $event->is_not_null());

    $another_event = dao('event')->find_by_name($name);
    otherwise_error_code('EVENT_DUPLICATED', $another_event->is_null() || $another_event->id === $event->id, [':event_id' => $another_event->id]);

    $event->name = $name;

    return true;
});/*}}}*/

if_post('/events/delete/*', function ($event_id)
{/*{{{*/
    $event = dao('event')->find($event_id);
    otherwise_error_code('EVENT_NOT_FOUND', $event->is_not_null());

    $event->delete();

    return true;
});/*}}}*/
